import prisma from "../prisma/prismaClient.js";

// 创建分享链接
const createShare = (userId, fileId, pwd = null, expires = null) => {
  return prisma.share.create({
    data: {
      userId,
      fileId,
      pwd,
      expires: expires ? new Date(expires) : null,
    },
  });
};
//获取分享总数和新增分享数
const getShareIncreaseInfo = async () => {
  const todayStart = new Date();
  todayStart.setHours(0, 0, 0, 0);

  const total = await prisma.share.count()
  const today = await prisma.share.count({
    where: {
      createdAt: {
        gte: todayStart,
      }
    }
  })
  return {
    total,
    today
  }
}

//获取最近n天的分享
const getRecentDaysShares = async (days = 7) => {
  const results = [];
  const today = new Date();

  // 确保只查询days天（包括今天）
  for (let i = days - 1; i >= 0; i--) {
    const date = new Date(today);
    date.setDate(today.getDate() - i);

    const startOfDay = new Date(date);
    startOfDay.setHours(0, 0, 0, 0);

    const endOfDay = new Date(date);
    endOfDay.setHours(23, 59, 59, 999);

    const count = await prisma.share.count({
      where: {
        createdAt: {
          gte: startOfDay,
          lte: endOfDay,
        },
      },
    });

    results.push({
      //获取最近n天的分享
      date: date.toISOString().split('T')[0],
      count,
    });
  }

  return results;
};

// 通过分享ID获取分享信息
const getShareById = (shareId) => {
  return prisma.share.findUnique({
    where: { id: shareId },
    include: {
      file: {
        select: {
          id: true,
          filename: true,
          type: true,
          size: true,
          isDeleted: true,
          isFolder: true,
          hash: true,
        },
      },
      user: {
        select: {
          id: true,
          username: true,
        },
      },
    },
  });
};

// 通过文件ID获取分享信息
const getShareByFileId = (fileId, userId) => {
  return prisma.share.findFirst({
    where: { fileId, userId },
    include: {
      user: {
        select: {
          id: true,
        },
      },
    },
  });
};

// 删除分享链接
const deleteShare = (shareId) => prisma.share.delete({ where: { id: shareId } });

// 批量删除
const deleteShares = (shareIds) => prisma.share.deleteMany({ where: { id: { in: shareIds } } });

// 获取用户的所有分享链接
const getUserShares = (userId) => {
  return prisma.share.findMany({
    where: { userId },
    include: {
      file: {
        select: {
          filename: true,
          type: true,
          size: true,
          isDeleted: true,
          isFolder: true,
        },
      },
    },
  });
};

// 更新分享信息
const updateShare = (shareId, updateData) => prisma.share.update({ where: { id: shareId }, data: updateData });

export default {
  createShare,
  getShareById,
  getShareByFileId,
  deleteShare,
  deleteShares,
  getUserShares,
  updateShare,
  getShareIncreaseInfo,
  getRecentDaysShares
};
